<template>
    <view class="search-page">
        <!-- 状态栏占位 -->
        <view class="status-bar" :style="{ height: statusBarHeight + 'px' }"></view>

        <!-- 顶部搜索栏 -->
        <view class="search-header" :style="{ paddingTop: searchBarPaddingTop + 'px' }">
            <view class="search-bar-container">
                <view class="back-icon" @click="goBack">
                    <uni-icons type="left" size="20" color="#333333"></uni-icons>
                </view>
                <view class="search-input-wrapper">
                    <input type="text" placeholder="输入商家、商品名称" v-model="searchKeyword" @confirm="handleSearch"
                        @input="onInput" class="search-input" :focus="isInputFocus" />
                    <view class="search-icon" @click="handleSearch" v-if="searchKeyword">
                        <uni-icons type="search" size="18" color="#999999"></uni-icons>
                    </view>
                    <view class="clear-icon" @click="clearSearch" v-if="searchKeyword">
                        <uni-icons type="clear" size="18" color="#999999"></uni-icons>
                    </view>
                </view>
            </view>
        </view>

        <!-- 搜索内容区域 -->
        <view class="search-content">
            <!-- 搜索结果列表 -->
            <view class="search-results" v-if="showResults">
                <view class="result-header" v-if="searchResultList.length > 0">
                    <text class="result-count">找到 {{ searchResultList.length }} 个结果</text>
                </view>
                <view class="waterfall-container">
                    <view class="waterfall-column" v-for="(column, colIndex) in waterfallColumns" :key="colIndex">
                        <view class="product-item-waterfall" v-for="(item, index) in column" :key="item.id || index"
                            @click="goToProductDetail(item)">
                            <image :src="item.img" mode="widthFix"></image>
                            <view class="product-info-waterfall">
                                <view class="product-title">{{ item.title }}</view>
                                <view class="product-synopsis">{{ item.synopsis }}</view>
                                <view class="product-price">
                                    <text class="price">¥{{ item.price }}</text>
                                    <text class="original-price" v-if="item.original_price">¥{{ item.original_price
                                    }}</text>
                                </view>
                            </view>
                        </view>
                    </view>
                </view>
                <!-- 无搜索结果 -->
                <view class="no-results" v-if="searchResultList.length === 0 && !loading">
                    <text>暂无搜索结果</text>
                </view>
            </view>

            <!-- 搜索建议区域（历史搜索 + 热门搜索） -->
            <view class="search-suggestions" v-else>
                <!-- 历史搜索 -->
                <view class="suggestion-section" v-if="historyList.length > 0">
                    <view class="section-header">
                        <text class="section-title">历史搜索</text>
                        <view class="section-title-wrapper">

                            <view class="clear-all-btn" v-if="isDeleteMode" @click="clearHistory">
                                <text class="clear-all-text">全部删除</text>
                            </view>
                            <view class="clear-history" @click="toggleDeleteMode">
                                <uni-icons type="trash" size="16" color="#999999"></uni-icons>
                            </view>
                        </view>

                    </view>
                    <view class="tag-list">
                        <view class="tag-item" v-for="(item, index) in historyList" :key="index">
                            <text class="tag-text" @click="!isDeleteMode && searchByKeyword(item)">{{ item }}</text>
                            <view class="tag-delete" v-if="isDeleteMode" @click.stop="deleteHistoryItem(index)">
                                <uni-icons type="closeempty" size="12" color="#999999"></uni-icons>
                            </view>
                        </view>
                    </view>
                </view>

                <!-- 热门搜索 -->
                <view class="suggestion-section" v-if="hotList.length > 0">
                    <view class="section-header">
                        <text class="section-title">热门搜索</text>
                    </view>
                    <view class="tag-list">
                        <view class="tag-item" v-for="(item, index) in hotList" :key="index"
                            @click="searchByKeyword(item)">
                            {{ item }}
                        </view>
                    </view>
                </view>
            </view>
        </view>
    </view>
</template>

<script>
import { typeApi } from '@/api/indexAPI.js';
import { public_img } from '@/static/public.js';

export default {
    data() {
        return {
            statusBarHeight: 0, // 状态栏高度
            searchBarPaddingTop: 0, // 搜索栏顶部内边距
            searchKeyword: '', // 搜索关键词
            isInputFocus: false, // 输入框是否聚焦
            showResults: false, // 是否显示搜索结果
            searchResultList: [], // 搜索结果列表
            loading: false, // 加载状态
            historyList: [], // 历史搜索列表
            hotList: [], // 热门搜索列表
            // 瀑布流列数
            waterfallColumnCount: 2,
            // 瀑布流列数据
            waterfallColumns: [[], []],
            // 全部商品数据（从分类接口获取）
            allProductList: [],
            // 删除模式状态
            isDeleteMode: false
        };
    },
    onLoad(options) {
        // 获取设备状态栏高度
        this.getStatusBarHeight();
        // 获取胶囊按钮信息并计算搜索栏padding
        this.getMenuButtonInfo();
        // 加载历史搜索
        this.loadHistory();
        // 加载热门搜索
        this.loadHotSearch();
        // 加载全部商品数据
        this.loadAllProducts();
        // 如果从首页跳转过来，获取关键词
        if (options && options.keyword) {
            this.searchKeyword = decodeURIComponent(options.keyword);
            // 注意：搜索会在 loadAllProducts 完成后自动执行
        } else {
            // 自动聚焦搜索框
            this.isInputFocus = true;
        }
    },
    methods: {
        // 获取设备状态栏高度
        getStatusBarHeight() {
            try {
                const systemInfo = uni.getSystemInfoSync();
                this.statusBarHeight = systemInfo.statusBarHeight || 0;
            } catch (err) {
                console.error('获取状态栏高度失败', err);
                this.statusBarHeight = 20;
            }
        },

        // 获取胶囊按钮信息并计算搜索栏padding
        getMenuButtonInfo() {
            try {
                // #ifdef MP-WEIXIN
                const menuButtonInfo = uni.getMenuButtonBoundingClientRect();
                if (menuButtonInfo) {
                    this.searchBarPaddingTop = menuButtonInfo.bottom - this.statusBarHeight + 10;
                } else {
                    this.searchBarPaddingTop = 44 + 10;
                }
                // #endif

                // #ifndef MP-WEIXIN
                this.searchBarPaddingTop = 44 + 10;
                // #endif
            } catch (err) {
                console.error('获取胶囊按钮信息失败', err);
                this.searchBarPaddingTop = 44 + 10;
            }
        },

        // 加载历史搜索
        loadHistory() {
            try {
                const history = uni.getStorageSync('searchHistory') || [];
                this.historyList = Array.isArray(history) ? history : [];
            } catch (err) {
                console.error('加载历史搜索失败', err);
                this.historyList = [];
            }
        },

        // 保存历史搜索
        saveHistory(keyword) {
            if (!keyword || !keyword.trim()) return;

            try {
                let history = uni.getStorageSync('searchHistory') || [];
                if (!Array.isArray(history)) {
                    history = [];
                }

                // 移除重复项
                history = history.filter(item => item !== keyword);
                // 添加到最前面
                history.unshift(keyword);
                // 最多保存10条
                if (history.length > 10) {
                    history = history.slice(0, 10);
                }

                uni.setStorageSync('searchHistory', history);
                this.historyList = history;
            } catch (err) {
                console.error('保存历史搜索失败', err);
            }
        },

        // 删除单个历史记录
        deleteHistoryItem(index) {
            try {
                // 从列表中移除
                this.historyList.splice(index, 1);
                // 更新存储
                uni.setStorageSync('searchHistory', this.historyList);
                // 如果删除后列表为空，退出删除模式
                if (this.historyList.length === 0) {
                    this.isDeleteMode = false;
                }
            } catch (err) {
                console.error('删除历史记录失败', err);
            }
        },

        // 切换删除模式
        toggleDeleteMode() {
            this.isDeleteMode = !this.isDeleteMode;
        },

        // 清除历史搜索（全部删除）
        clearHistory() {
            try {
                uni.removeStorageSync('searchHistory');
                this.historyList = [];
                // 清除后退出删除模式
                this.isDeleteMode = false;
            } catch (err) {
                console.error('清除历史搜索失败', err);
            }
        },

        // 加载热门搜索（可以从接口获取，这里先用默认数据）
        loadHotSearch() {
            // TODO: 如果后端有热门搜索接口，可以在这里调用
            // 暂时使用默认数据
            this.hotList = ['便利贴', '铅笔', '复写笔', '印刷纸', '记号笔'];
        },

        // 加载全部商品数据（从分类接口获取）
        async loadAllProducts() {
            try {
                const response = await typeApi.getTypeList();

                if (response && response.code === 1 && response.data) {
                    // 将所有分类下的商品合并成一个数组
                    const allProducts = [];
                    const productMap = new Map(); // 用于去重，key为商品ID

                    if (Array.isArray(response.data)) {
                        response.data.forEach(category => {
                            if (category.list && Array.isArray(category.list)) {
                                category.list.forEach(product => {
                                    // 使用商品ID作为唯一标识符进行去重
                                    const productId = product.id || product.goods_id || product.gid;

                                    // 如果商品ID不存在或已存在，跳过
                                    if (!productId || productMap.has(productId)) {
                                        return;
                                    }

                                    // 处理图片路径
                                    const processedProduct = {
                                        ...product,
                                        img: product.img && product.img.startsWith('http')
                                            ? product.img
                                            : (public_img + (product.img || ''))
                                    };

                                    allProducts.push(processedProduct);
                                    productMap.set(productId, true);
                                });
                            }
                        });
                    }
                    this.allProductList = allProducts;
                    console.log('加载全部商品数据成功，共', allProducts.length, '个商品（已去重）');

                    // 如果页面加载时有关键词，数据加载完成后自动搜索
                    if (this.searchKeyword && this.searchKeyword.trim()) {
                        this.handleSearch();
                    }
                } else {
                    console.warn('获取分类数据失败:', response);
                    this.allProductList = [];
                }
            } catch (error) {
                console.error('加载全部商品数据失败:', error);
                this.allProductList = [];
            }
        },

        // 输入框输入事件
        onInput(e) {
            this.searchKeyword = e.detail.value;
        },

        // 清除搜索关键词
        clearSearch() {
            this.searchKeyword = '';
            this.showResults = false;
            this.searchResultList = [];
        },

        // 执行搜索（本地模糊匹配）
        handleSearch() {
            const keyword = this.searchKeyword.trim();
            if (!keyword) {
                uni.showToast({
                    title: '请输入搜索内容',
                    icon: 'none'
                });
                return;
            }

            // 如果商品数据还未加载完成，等待加载
            if (this.allProductList.length === 0 && !this.loading) {
                uni.showToast({
                    title: '数据加载中，请稍候...',
                    icon: 'none'
                });
                return;
            }

            // 保存到历史搜索
            this.saveHistory(keyword);

            // 显示搜索结果
            this.showResults = true;
            this.loading = true;

            // 使用 filter 进行模糊匹配
            const lowerKeyword = keyword.toLowerCase();
            const filteredList = this.allProductList.filter(item => {
                // 匹配商品标题
                const titleMatch = item.title && item.title.toLowerCase().includes(lowerKeyword);
                // 匹配商品简介
                const synopsisMatch = item.synopsis && item.synopsis.toLowerCase().includes(lowerKeyword);
                // 可以添加更多匹配字段，如商家名称等
                // const merchantMatch = item.merchant && item.merchant.toLowerCase().includes(lowerKeyword);

                return titleMatch || synopsisMatch;
            });

            // 对搜索结果进行去重处理
            const uniqueList = [];
            const seenIds = new Set();

            filteredList.forEach(item => {
                const productId = item.id || item.goods_id || item.gid;
                // 如果商品ID不存在或已存在，跳过
                if (productId && !seenIds.has(productId)) {
                    uniqueList.push(item);
                    seenIds.add(productId);
                }
            });

            this.loading = false;
            this.searchResultList = uniqueList;

            // 构建瀑布流数据
            this.buildWaterfallData();

            // 如果没有搜索结果，显示提示
            if (uniqueList.length === 0) {
                console.log('未找到匹配的商品');
            } else {
                console.log('找到', uniqueList.length, '个匹配的商品（已去重）');
            }
        },

        // 构建瀑布流数据
        buildWaterfallData() {
            // 初始化列数组
            const columns = Array.from({ length: this.waterfallColumnCount }, () => []);

            // 将商品列表按顺序分配到各列
            this.searchResultList.forEach((item, index) => {
                const columnIndex = index % this.waterfallColumnCount;
                columns[columnIndex].push(item);
            });

            // 更新瀑布流列数据
            this.waterfallColumns = columns;
        },

        // 通过关键词搜索（点击历史搜索或热门搜索）
        searchByKeyword(keyword) {
            this.searchKeyword = keyword;
            this.handleSearch();
        },

        // 跳转到商品详情
        goToProductDetail(item) {
            if (!item || !item.id) {
                return;
            }
            uni.navigateTo({
                url: `/pages/product/index?id=${item.id}`
            });
        },

        // 返回上一页
        goBack() {
            uni.navigateBack({
                delta: 1
            });
        }
    }
};
</script>

<style lang="scss" scoped>
.search-page {
    width: 100%;
    min-height: 100vh;
    background-color: #f5f5f5;
    display: flex;
    flex-direction: column;
}

/* 状态栏占位 */
.status-bar {
    width: 100%;
    background-color: #ffffff;
}

/* 顶部搜索栏 */
.search-header {
    width: 100%;
    background-color: #ffffff;
    padding: 0 30rpx 20rpx;
    box-sizing: border-box;
}

.search-bar-container {
    display: flex;
    align-items: center;
    gap: 20rpx;
}

.back-icon {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 40rpx;
    height: 40rpx;
}

.search-input-wrapper {
    flex: 1;
    position: relative;
    display: flex;
    align-items: center;
    border-radius: 50rpx;
    padding: 0 30rpx;
    height: 70rpx;
    border: 1px solid #8d8d8c;
}

.search-input {
    flex: 1;
    height: 100%;
    font-size: 28rpx;
    color: #333333;
}

.search-icon,
.clear-icon {
    margin-left: 20rpx;
    display: flex;
    align-items: center;
    justify-content: center;
}

/* 搜索内容区域 */
.search-content {
    flex: 1;
    padding: 30rpx 0;
    box-sizing: border-box;
}

/* 搜索结果 */
.search-results {
    width: 100%;
}

.result-header {
    margin-bottom: 20rpx;
    padding: 0 30rpx;
}

.result-count {
    font-size: 24rpx;
    color: #999999;
}

/* 瀑布流容器 */
.waterfall-container {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    padding: 0 30rpx 20rpx;
}

.waterfall-column {
    display: flex;
    flex: 1;
    flex-direction: column;
    margin-right: 15rpx;
}

.waterfall-column:last-child {
    margin-right: 0;
}

.product-item-waterfall {
    background-color: #fff;
    border-radius: 16rpx;
    overflow: hidden;
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.05);
    margin-bottom: 7px;
    padding: 5px;
}

.product-item-waterfall image {
    width: 100%;
    border-radius: 5.5px;
}

.product-info-waterfall {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
}

.product-title {
    font-size: 14px;
    color: #505050;
    margin-bottom: 3px;
}

.product-synopsis {
    font-size: 13px;
    color: #8b8b8c;
    margin-bottom: 10px;
    flex: 1;
    width: 150px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.product-price {
    display: flex;
    align-items: center;
}

.price {
    font-size: 14px;
    color: #ff4757;
    margin-right: 10rpx;
}

.original-price {
    font-size: 24rpx;
    color: #999;
    text-decoration: line-through;
}

.no-results {
    text-align: center;
    padding: 100rpx 0;
    color: #999999;
    font-size: 28rpx;
}

/* 搜索建议区域 */
.search-suggestions {
    width: 100%;
    padding: 0 30rpx;
    box-sizing: border-box;
}

.suggestion-section {
    margin-bottom: 40rpx;
}

.section-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 20rpx;
}

.section-title-wrapper {
    display: flex;
    align-items: center;
    gap: 20rpx;
}

.section-title {
    font-size: 32rpx;
    color: #333333;
    font-weight: bold;
}

.clear-all-btn {
    padding: 8rpx 20rpx;
    background-color: white;
    border-radius: 30rpx;
    display: flex;
}

.clear-all-text {
    font-size: 24rpx;
    color: black;
}

.clear-history {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 10rpx;
}

.tag-list {
    display: flex;
    flex-wrap: wrap;
    gap: 20rpx;
}

.tag-item {
    position: relative;
    padding: 12rpx 24rpx;
    background-color: #ffffff;
    border: 1rpx solid #e0e0e0;
    border-radius: 50rpx;
    font-size: 26rpx;
    color: #333333;
    white-space: nowrap;
    display: inline-block;
}

.tag-text {
    display: inline-block;
}

.tag-delete {
    position: absolute;
    top: -9rpx;
    right: -8rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 32rpx;
    height: 32rpx;
    background-color: #ffffff;
    border-radius: 50%;
}
</style>
